package org.argus.job.server.system.management.controller;

import java.util.Arrays;
import java.util.List;

import org.argus.common.core.domain.R;
import org.argus.job.common.enums.TimeExpressionType;
import org.argus.job.common.model.JobInfo;
import org.argus.job.common.request.http.RunJobRequest;
import org.argus.job.common.request.http.SaveJobInfoRequest;
import org.argus.job.server.system.management.model.JobInfoSearchReq;
import org.argus.job.server.system.management.service.JobInfoService;
import org.argus.job.server.system.scheduler.TimingStrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.ApiOperation;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/8/6
 */
@RestController
@RequestMapping("/job-info/v1/job-info")
public class JobInfoController {

    @Autowired
    private JobInfoService jobInfoService;

    @Autowired
    private TimingStrategyService timingStrategyService;

    @GetMapping("/page")
    public R<Page<JobInfo>> page(JobInfoSearchReq pageReq, Page page) {
        return R.ok(jobInfoService.page(page, pageReq));
    }

    @PostMapping("/list")
    public R<List<JobInfo>> list(@RequestBody JobInfoSearchReq searchReq) {
        return R.ok(jobInfoService.list(searchReq));
    }

    @PostMapping("/save")
    public R<Void> add(@RequestBody SaveJobInfoRequest jobInfo) {
        jobInfoService.saveJob(jobInfo);
        return R.ok();
    }

    @ApiOperation("修改应用状态")
    @PutMapping("/status")
    public R<Void> updateStatus(@RequestBody JobInfo jobInfo) {
        jobInfoService.updateStatus(jobInfo);
        return R.ok();
    }

    @GetMapping("/time-expression/validate")
    public R<List<String>> validateTimeExpression(TimeExpressionType timeExpressionType, String timeExpression,
                                                  @RequestParam(required = false) Long startTime,
                                                  @RequestParam(required = false) Long endTime) {
        try {
            timingStrategyService.validate(timeExpressionType, timeExpression, startTime, endTime);
            return R.ok(timingStrategyService.calculateNextTriggerTimes(timeExpressionType, timeExpression, startTime, endTime));
        } catch (Exception e) {
            return R.ok(Arrays.asList(e.getMessage()));
        }
    }

    @PostMapping("/run-job")
    public R<Long> runJob(@RequestBody RunJobRequest runJobRequest) {
        return R.ok(jobInfoService.runJob(runJobRequest.getAppId(), runJobRequest.getJobId(),
                runJobRequest.getInstanceParams(), null));
    }
}
